package servicios;

import java.util.Date;

import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


@Singleton
public class Notificacion {
	
			
	private static ConnectionFactory connectionFactory=null;
	
	private static Queue mailQueue;
	
	private Context ctx;
	private Connection connectionMail;
	private Session sessionMail;
	private MessageProducer messageProducerMail=null; 
	
	
	public void conectarMailQueue(){
				
		String destinationName = "queue/test"; 
		
		try {
				ctx = new InitialContext();			
				connectionFactory = (ConnectionFactory)ctx.lookup("java:/ConnectionFactory"); 
		
				mailQueue = (Queue)ctx.lookup(destinationName); 
				connectionMail = connectionFactory.createConnection(); 
				sessionMail = connectionMail.createSession(false, Session.AUTO_ACKNOWLEDGE);
				
				messageProducerMail = sessionMail.createProducer(mailQueue); 
				connectionMail.start();
				
			} catch (NamingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 	 
		//log.info("Conectado");
	}
	
	public void enviarMensaje(String asunto, String texto, String destinatarios){
		 
		//log.info("Enviar Correo");
		
		if (messageProducerMail == null){
			conectarMailQueue();
		}
		try {
			
			String[] correos= destinatarios.split(";");
			
			MapMessage message = sessionMail.createMapMessage();
			message.setString("asunto", asunto);
			message.setString("texto", texto);
			for(int i=0;i<correos.length;i++){
						
				message.setString("destinatario", correos[i]);
				message.setLong("fecha", new Date().getTime());
				
				System.out.println("Enviando Mail (Cola) >> asunto=" + asunto +
	                    " destino=" + correos[i] + 
	                    " mensaje="  + texto);
					
				messageProducerMail.send(message);
				
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
	}
	@PreDestroy
	public void destroy(){
		//log.info("Destroy Connection JMS");			
	}
	
	
	
	
		
	
}
